let id = localStorage.getItem("index");

$.ajax({
  url: "/goods/cate",
  method: "get",
  success(res) {
    const arr = res.data.map(function (item) {
      return `
      <li><a href="">${item.name}</a></li>
      `;
    });
    $(".cate-list-fix ul").html(arr.join(""));
    $(".cate-list-fix ul li")
      .eq(id - 1)
      .addClass("active");
  },
});
$(".cate-list-fix").on("click", "li", function (e) {
  e.preventDefault();
  $(this).addClass("active").siblings().removeClass("active");
  let indexId = $(this).index() + 1;
  render(indexId);
});

// 封装渲染函数 根据cate_id渲染
function render(id) {
  $.ajax({
    url: "/goods",
    method: "get",
    data: {
      cate_id: id,
    },
    success(res) {
      console.log(res);
      const str = res.data.list
        .map((item, i) => {
          return `
            <li>
        <img src=${item.img} alt="">
        <h3>${item.title}</h3>
        <p>
            <span>${item.price}</span>
            <span class='add'>+</span>
        </p>
    </li>
            `;
        })
        .join("");
      $(".good-list ul").html(str);
    },
  });
}
render(id);
// 点击加入购物车
$(".good-list").on("click", ".add", function () {
  const title = $(this).parents().siblings("h3").html();
  const price = +$(this).siblings().html().substring(1);
  console.log(price);
  const img = $(this).parents().siblings("img").prop("src");
  $.ajax({
    method: "POST",
    url: "/cart/create",
    headers: {
      Authorization: localStorage.getItem("token"),
    },
    dataType: "json",
    contentType: "application/json",
    data: JSON.stringify({
      goods_id: 23,
      title,
      img,
      price,
      cate_id: 1,
      buy_num: 1,
      is_selected: 1,
    }),
    success: function (res) {
      console.log(res);
    },
  });
});
